package com.ldzl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ldzl.dto.AddOutboundDTO;
import com.ldzl.pojo.CkProductSales;
import com.ldzl.pojo.CkProductSalesLine;
import com.ldzl.pojo.CkStockDetail;
import com.ldzl.pojo.ScSalesOrder;
import com.ldzl.service.CkProductSalesLineService;
import com.ldzl.service.CkProductSalesService;
import com.ldzl.mapper.CkProductSalesMapper;
import com.ldzl.service.CkStockDetailService;
import com.ldzl.service.ScSalesOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @author 风止
* @description 针对表【ck_product_sales(销售出库单表)】的数据库操作Service实现
* @createDate 2025-07-24 17:24:38
*/
@Service
public class CkProductSalesServiceImpl extends ServiceImpl<CkProductSalesMapper, CkProductSales>
    implements CkProductSalesService{

    @Autowired
    private CkStockDetailService sds; //库存服务
    @Autowired
    private CkProductSalesLineService psls; //销售出库单行服务
    @Autowired
    private ScSalesOrderService sos; //销售订单服务

    /**
     * 查询待质检的销售出库单
     * @param sales_code
     * @param sales_name
     * @return
     */
    @Override
    public List<CkProductSales> selectCkProductSales(String sales_code, String sales_name) {
        return super.baseMapper.selectCkProductSales(sales_code, sales_name);
    }

    /**
     * 修改销售出库单状态
     * @param status
     * @param sales_id
     * @return
     */
    @Override
    public boolean updateCkProductSalesStatusStatus(String status, Long sales_id) {
        return super.baseMapper.updateCkProductSalesStatusStatus(status, sales_id) > 0;
    }

    /**
     * 查询所有销售出库单
     * @param sales
     * @return
     */
    @Override
    public List<CkProductSales> selectProduct_Sales(CkProductSales sales) {
        return super.baseMapper.selectProduct_Sales( sales);
    }

    /**
     * 添加出库单
     * @param outboundDTO
     * @return
     */
    @Override
    public int insertProduct_Sales(AddOutboundDTO outboundDTO) {
        //获取当前日期
        Date date = new Date();
        //获取提交的出库单信息
        CkProductSales sales = outboundDTO.getSales();

        //查询原本的销售出库订单
        CkProductSales oldSales = super.getOne(new QueryWrapper<CkProductSales>()
                .eq("sales_name",sales.getSales_name())
                .eq("is_delete",0)
        );

        //判断是否为修改
        boolean isUpdate = outboundDTO.getSales().getSales_id() != null;
        if(isUpdate){
            //重新按id查询一遍
            oldSales = super.getOne(new QueryWrapper<CkProductSales>()
                    .eq("sales_id",sales.getSales_id())
                    .eq("is_delete",0)
            );

            //判断名称是否重复
            if(!oldSales.getSales_name().equals(sales.getSales_name())){
                //查询原本的销售出库订单
                CkProductSales s = super.getOne(new QueryWrapper<CkProductSales>()
                        .eq("sales_name",sales.getSales_name())
                        .eq("is_delete",0)
                );
                if(s != null)
                    return 4; //名称重复
            }

            //判断销售订单是否修改
            if(!sales.getOrder_code().equals(oldSales.getOrder_code())){
                //移除原销售订单下的明细
                List<CkProductSalesLine> lines = psls.selectCkProductSalesLine(sales.getSales_id());
                //要移除的产品集合
                List<CkProductSalesLine> salesLines = new ArrayList<>();
                lines.forEach(line -> {
                    CkProductSalesLine salesLine = new CkProductSalesLine();
                    salesLine.setLine_id(line.getLine_id());
                    salesLine.setIs_delete("1");
                    salesLines.add(salesLine);
                });
                if(!psls.saveOrUpdateBatch(salesLines))
                    return 2; //批量更新失败
                //修改销售订单的状态
                ScSalesOrder salesOrder = new ScSalesOrder();
                salesOrder.setSales_order_id(oldSales.getSales_order_id());
                salesOrder.setStatus("1"); //修改回 已确定
                salesOrder.setUpdate_by(sales.getUpdate_by());
                salesOrder.setUpdate_time(date);
                if(!sos.saveOrUpdate(salesOrder)){
                    System.out.println("修改销售订单状态失败："+sales.getSales_order_id());
                    return 3; //修改销售订单状态失败
                }
            }
        }else{
            //判断名称是否重复
            if(oldSales != null){
                return 4; //名称重复
            }
        }

        //修改销售订单的状态
        ScSalesOrder salesOrder = new ScSalesOrder();
        salesOrder.setSales_order_id(sales.getSales_order_id());
        salesOrder.setStatus("2"); //已完成
        salesOrder.setUpdate_by(sales.getUpdate_by());
        salesOrder.setUpdate_time(date);
        if(!sos.saveOrUpdate(salesOrder)){
            System.out.println("修改销售订单状态失败："+sales.getSales_order_id());
            return 3; //修改销售订单状态失败
        }


        //移除地址中的空格
        sales.setAddress(sales.getAddress().replaceAll("\\s+", ""));
        //添加出库日期
        //sales.setSales_date(date);
        sales.setCreate_time( date);
        sales.setUpdate_time( date);

        //获取提交的出库单产品信息
        List<CkProductSalesLine> lines = outboundDTO.getLines();

        //新增出库单
        if(super.saveOrUpdate(sales)){
            lines.forEach(line -> {
                line.setSales_id(sales.getSales_id());
                line.setStatus("1"); //默认待质检
                //查询该产品的批次信息
                List<CkStockDetail> listDetail = sds.list(new QueryWrapper<CkStockDetail>()
                        .eq("item_code", line.getProduct_code())
                );
                line.setBatch_id(listDetail.get(0).getBatch_id());
                line.setBatch_code(listDetail.get(0).getBatch_code());
                //获取创建者和修改者
                line.setCreate_by(sales.getCreate_by());
                line.setCreate_time(date);
                line.setUpdate_by(sales.getUpdate_by());
                line.setUpdate_time(date);
            });

            if(psls.saveOrUpdateBatch(lines))
                return 1; //保存成功
        }
        return 2;//保存失败
    }

    /**
     * 销售出库
     * @param sales_id
     * @param update_by
     * @return
     */
    @Override
    public boolean warehouseOutbound(Long sales_id, String update_by) {
        //加上出库时间
        Date date = new Date();
        CkProductSales sales = new CkProductSales();
        sales.setSales_id(sales_id);
        sales.setSales_date( date);
        sales.setUpdate_by(update_by);
        sales.setUpdate_time( date);
        if(!super.saveOrUpdate( sales))
            return false;
        if(updateCkProductSalesStatusStatus("6", sales_id))
            return psls.warehouseOutbound(sales_id,update_by);
        return false;
    }

    /**
     * 删除销售订单
     * @param sales_id
     * @param update_by
     * @return
     */
    @Override
    public boolean updateSales_delete(Long sales_id, String update_by) {
        Date date = new Date();

        //修改销售订单的状态
        CkProductSales sales = super.getOne(new QueryWrapper<CkProductSales>()
                .eq("sales_id",sales_id)
                .eq("is_delete",0)
        );
        ScSalesOrder salesOrder = new ScSalesOrder();
        System.out.println("测试获取的销售订单ID："+sales.getSales_order_id());
        salesOrder.setSales_order_id(sales.getSales_order_id());
        salesOrder.setStatus("1"); //已确定
        salesOrder.setUpdate_by(update_by);
        salesOrder.setUpdate_time(date);
        if(!sos.saveOrUpdate(salesOrder)){
            return false; //修改销售订单状态失败
        }

        sales = new CkProductSales();
        sales.setSales_id(sales_id);
        sales.setSales_date( date);
        sales.setUpdate_by(update_by);
        sales.setUpdate_time( date);
        sales.setIs_delete("1");
        if(super.saveOrUpdate( sales))
            return true;
        return false;
    }

    /**
     * 批量删除销售订单
     * @param list_sales_id
     * @param update_by
     * @return
     */
    @Override
    public boolean deleteBatch(List<Long> list_sales_id, String update_by) {
        Date date = new Date(); //获取当前时间
        List<CkProductSales> salesList = new ArrayList<>(); //要移除的采购订单集合
        for(Long sales_id : list_sales_id){
            CkProductSales sales = super.getOne(new QueryWrapper<CkProductSales>()
                    .eq("sales_id",sales_id)
                    .eq("is_delete",0)
            );
            //只有待质检的订单才需要修改销售订单的状态
            if(sales.getStatus().equals("1")){
                ScSalesOrder salesOrder = new ScSalesOrder();
                System.out.println("测试获取的销售订单ID："+sales.getSales_order_id());
                salesOrder.setSales_order_id(sales.getSales_order_id());
                salesOrder.setStatus("1"); //已确定
                salesOrder.setUpdate_by(update_by);
                salesOrder.setUpdate_time(date);
                if(!sos.saveOrUpdate(salesOrder)){
                    return false; //修改销售订单状态失败
                }
            }
            sales = new CkProductSales();
            sales.setSales_id(sales_id);
            sales.setSales_date( date);
            sales.setUpdate_by(update_by);
            sales.setUpdate_time( date);
            sales.setIs_delete("1");

            salesList.add(sales); //添加要移除的采购订单
        }
        return super.saveOrUpdateBatch(salesList);
    }


}




